#include "download.h"
#include "head.h"
//下载-----服务端
#define M 104876
int sendFile(char filename[],int sdf)
{
   train_t t;
   bzero(&t,sizeof(t));
   t.dataLength=strlen(filename);
   strcpy(t.buf,filename);
   //printf("文件名字%s\n",t.buf);
   int file=send(sdf,&t,sizeof(int)+t.dataLength,MSG_NOSIGNAL);//发送下载文件名字长度+文件名字
   ERROR_CHECK(file,-1,"发送服务端被下载文件名字长度+文件名字");
   int fd=open(t.buf,O_RDWR);
   //FILE *fp=fopen(t.buf,"r+");
   bzero(&t,sizeof(t));
   struct stat st;
   int retstat=fstat(fd,&st);
   ERROR_CHECK(retstat,-1,"fstat");
   long localsize=st.st_size; //服务端被下载文件大小
   printf("服务端被下载文件大小%ldM\n",localsize/M);
   t.dataLength=sizeof(st.st_size);
   memcpy(t.buf,&st.st_size,sizeof(st.st_size));
   int ret6=send(sdf,&t,t.dataLength+sizeof(t.dataLength),MSG_NOSIGNAL);//发送客户端文件的大小长度+文件大小
   ERROR_CHECK(ret6,-1,"发送服务端被下载文件的大小长度与大小");
   long filesize;
   int dataLength;
   int ret1=recv(sdf,&dataLength,sizeof(int),MSG_WAITALL); //接收客户端同名文件大小长度
   int ret2=recv(sdf,&filesize,dataLength,MSG_WAITALL); //接收客户端同名文件大小
   ERROR_CHECK(ret1,-1,"接收服客户端同名文件大小长度");
   char* p=(char*)mmap(NULL,st.st_size,PROT_READ,MAP_SHARED,fd,0);
   if(p!=NULL)
   {
     printf("mmap成功\n");
   }
   off_t index=0;
   if(filesize!=0)
   {
      printf("断点重传\n");
      printf("客户端同名文件大小%ldM\n",filesize/M);
      index=filesize;
   }
   int i=0;
   while(index<localsize)
   {
     if(localsize-index >= sizeof(t.buf))
     {
       t.dataLength=sizeof(t.buf);
     }
     else
     {
       t.dataLength=localsize-index;
     }
       memcpy(t.buf,p+index,t.dataLength);
       index=index+t.dataLength;
       int ret7=send(sdf,&t,sizeof(int)+t.dataLength,MSG_NOSIGNAL);
       //printf("%5.2lf%% %ld\r",100.0*index/localsize,index);
       //fflush(stdout);
    }
    t.dataLength=0;
    send(sdf,&t,sizeof(int),MSG_NOSIGNAL);
    int ret8=munmap(p,st.st_size);
    ERROR_CHECK(ret8,-1,"解除mmap映射");
    printf("发送文件大小: %ldM\n",index/M);
    close(fd);
    return 0;
   }


